'use strict';

var P2PSpider = require('../lib');
var StringDecoder = require('string_decoder').StringDecoder;
var mysql = require("mysql2");
var connection = mysql.createConnection({
    user: 'root',
    password:'123456',
    database: 'p2pspider',
    host: '0.0.0.0'
});
connection.config.namedPlaceholders = true;

var p2p = P2PSpider({
    nodesMaxSize: 400,   // be careful
    maxConnections: 200, // be careful
    timeout: 5000
});


var decoder = new StringDecoder('utf8');

p2p.ignore(function (infohash, rinfo, callback) {
    // false => always to download the metadata even though the metadata is exists.
    var theInfohashIsExistsInDatabase = true;
    callback(theInfohashIsExistsInDatabase);
});

p2p.on('metadata', function (metadata) {
    
        var name1 = '';
        if(metadata.info.name) name1 = metadata.info.name;
        var name = decoder.write(name1);
        var pieceLength = metadata.info["piece length"];
        if(metadata.info.pieces)
            var pieces = metadata.info.pieces.toString();
        var address = metadata.address;
        var port = metadata.port;
        var infohash = metadata.infohash;
        var magnet = metadata.magnet;
        var now = new Date();
        var files = metadata.info.files;
        console.log(name);   
    
        connection.execute("select * from dht_info where magnet = '"+ magnet +"'", {}, function(err, rows){
            if(err){
                console.log(err);
                return;
            }
            if(rows && rows.length === 0){
                connection.execute('insert into dht_info (name, pieceLength, pieces, address, port, infohash, magnet, updateTime) values (:name , :pieceLength , :pieces , :address , :port , :infohash , :magnet, :updateTime )',
                    { name:name, pieceLength:pieceLength, pieces:"", address:address, port:port, infohash: infohash, magnet: magnet, updateTime:now }, function(err, rows) {
                        if(err){
                            console.log(err);
                        }
                        if(rows){
                            var insertId = rows.insertId;
                            if(files){
                                for(var i=0;i<files.length; i++){
                                    var item = files[i];
                                    if(item.path){
                                        if(item.path[0])
                                            connection.execute('insert into files (dht_info_id, length ,name) values (:dht_info_id , :length , :name )', { dht_info_id:insertId, length: item.length, name: decoder.write(item.path[0]) });
                                    }
                                }
                            }
                            console.log("Add Success");
                        }
                    });
            }else{
                var hot = rows[0].hot + 1;
                var magnet1 = rows[0].magnet;
                connection.execute('update dht_info set hot = :hot, updateTime = :updateTime where magnet = :magnet', { hot:hot, updateTime:now, magnet:magnet1}, function(err, rows){
                    if(err){
                        console.log(err);
                    }
                    if(rows){
                        console.log("Update Success!");
                    }
                })
            }
        });
    });

p2p.listen(6881, '0.0.0.0');
